package com.lz.comm.net

import android.net.ParseException
import com.google.gson.JsonParseException
import org.apache.http.conn.ConnectTimeoutException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import javax.net.ssl.SSLHandshakeException

 class RespException(cause: Throwable, val code: Int) : Exception(cause) {

    companion object {
        //未知错误
        const val UNKNOWN = 1000

        //解析错误
        const val PARSE_ERROR = 1001

        //网络错误
        const val NETWORK_ERROR = 1002

        //协议出错
        const val HTTP_ERROR = 1003

        //证书出错
        const val SSL_ERROR = 1005

        //连接超时
        const val TIMEOUT_ERROR = 1006

        //服务端异常处理(前后协议)
        const val SERVER_ERROR = 1007

        fun handleThrowable(cause: Throwable): RespException {
            val code = when (cause) {
                is HttpException -> HTTP_ERROR
                is ServerException -> SERVER_ERROR
                is JsonParseException, is JSONException, is ParseException -> PARSE_ERROR
                is ConnectException -> NETWORK_ERROR
                is SSLHandshakeException -> SSL_ERROR
                is ConnectTimeoutException, is SocketTimeoutException -> TIMEOUT_ERROR
                else -> UNKNOWN
            }
            return RespException(cause, code)
        }
    }

}